package by.msokoloff.javaweb2015.services.impl;

import java.math.BigDecimal;
import java.util.List;

import javax.inject.Inject;
import javax.persistence.metamodel.SingularAttribute;

import org.springframework.stereotype.Service;

import by.msokoloff.javaweb2015.dataaccess.TripOrderDao;
import by.msokoloff.javaweb2015.datamodel.Extra;
import by.msokoloff.javaweb2015.datamodel.Flight;
import by.msokoloff.javaweb2015.datamodel.TripOrder;
import by.msokoloff.javaweb2015.services.TripOrderService;

@Service
public class TripOrderServiceImpl implements TripOrderService {

	@Inject
	private TripOrderDao dao;

	@Override
	public TripOrder get(Integer id) {
		return dao.getById(id);
	}

	@Override
	public List<TripOrder> getAll() {
		return dao.getAll();
	}

	@Override
	public void createOrUpdate(TripOrder tripOrder) {
		if (tripOrder.getId() == null) {
			dao.create(tripOrder);
		} else {
			dao.update(tripOrder);
		}
	}

	@Override
	public void delete(TripOrder tripOrder) {
		dao.delete(tripOrder.getId());
	}

	@Override
	public void deleteAll() {
		dao.deleteAll();
	}

	@Override
	public BigDecimal getPrice(TripOrder tripOrder) {

		// TODO Calculate order price

		tripOrder = dao.getDetailed(tripOrder.getId());

		BigDecimal price = new BigDecimal(0);

		for (Flight f : tripOrder.getFlights()) {
			price = price.add(f.getTariff());
			price = price.add(f.getDepartureAirport().getTaxes());
		}

		for (Extra e : tripOrder.getExtras()) {
			price = price.add(e.getPrice());
		}

		return price;
	}

	@Override
	public long getCount() {
		return dao.getCount();
	}

	@Override
	public List<TripOrder> getAll(SingularAttribute<TripOrder, ?> sortParam, boolean ascending, int first, int count) {
		return dao.getAll(sortParam, ascending, first, count);
	}

	@Override
	public List<TripOrder> getByField(SingularAttribute<TripOrder, ?> attr, Object val) {
		return dao.getByField(attr, val);
	}

}
